import {
	hideLoading,
	showLoading,
	toast
} from "./native/index.js"

import { baseUrl } from '../config/index.js'

const reLogin = () => {
	uni.showModal({
		title: "温馨提示",
		content: "登录失效，重新登录",
		showCancel: false,
		success() {
			// 清除缓存
			uni.clearStorageSync()
			uni.reLaunch({
				url: '/pages/mine/mine'
			})
		}
	})

}

export const post = (url, data, error = 2) => {
	const token = uni.getStorageSync('token')

	let level
	let loadingMessage = '加载中...'
	if (typeof error === 'number') {
		level = error
	} else {
		level = error.level
		loadingMessage = error.message
	}

	return new Promise((resovle, reject) => {
		console.log(new Date().getTime(), uni.getStorageSync('tokenTime'))
		if (new Date().getTime() - uni.getStorageSync('tokenTime') > 2 * 60 *
			60 * 1000 && !['/doc/list', '/doc/detail', '/product/list',
				'/wxLogin',
				'/wxConfig'
			].includes(url)) {
			reLogin()
		} else {
			if (level > 0) {
				showLoading(loadingMessage)
			}
			uni.request({
				url: baseUrl + url,
				data,
				method: "POST",
				header: { token },
				success: (res) => {
					console.log('接口响应Data', url, res.data);
					if (level > 0) {
						hideLoading()
					}
					if (res.data?.msg?.code === 200) {
						resovle(res.data.data)
					} else if (res.data?.msg?.code === 401) {
						if (level === 2) {
							toast("登录失效")
						}
						// 清除缓存
						uni.clearStorageSync()
						uni.reLaunch({
							url: '/pages/index/index'
						})
					} else {
						const message = res.data?.msg?.message ?? '接口异常'
						if (level === 2) {
							toast(message)
						}
						if (level === 3) {
							uni.showModal({
								title: "温馨提示",
								content: message,
								showCancel: false
							})
						}
						reject(message)
					}
				},
				fail: (e) => {
					const message = e.message || '接口异常'
					console.log(e)
					if (level > 0) {
						hideLoading()
					}
					if (level === 2) {
						toast(message)
					}
					if (level === 3) {
						uni.showModal({
							title: "温馨提示",
							content: message,
							showCancel: false
						})
					}
					reject(message)
				}
			});
		}

	})
}